import Vue from 'vue'
import Vuex from 'vuex'
// 导入localStorage封装的方法
import { setTokenObj, getTokenObj } from '../utils/storage.js'
import { setUserInfo, getUserInfo } from '../utils/storageUserInfo.js'
Vue.use(Vuex)
// getTokenObj() || {} : 如果getTokenObj的返回值是null，则initTokenObj是一个空对象
// 空对象的token属性是undefined，而不会报错
const initTokenObj = getTokenObj() || {}
const initUserObj = getUserInfo() || {}
export default new Vuex.Store({
  // 保存公共数据
  state: {
    tokenInfo: {
      token: initTokenObj.token || '',
      refresh_token: initTokenObj.refresh_token || ''
    }
  },
  // state中的数据通过mutatins修改
  mutations: {
    // mutation中是各个函数, 第一个参数是当前的state, 第二个是要传入的数据：载荷
    mSetTokenInfo (state, newTokenInfo) {
      state.tokenInfo = newTokenInfo

      // 保存到本地localstorage
      setTokenObj(newTokenInfo)
    }
  },
  getters: {
    isLogin (state) {
      return !!state.tokenInfo.token
    }
  },
  actions: {
  },
  // 里面可以放独立的模块
  modules: {
    userInfo: {
      // 命名空间
      namespaced: true,
      // 用户个人信息
      state: {
        birthday: initUserObj.birthday || '',
        gender: initUserObj.gender || 1,
        id: initUserObj.id || '',
        mobile: initUserObj.mobile || '',
        name: initUserObj.name || '',
        photo: initUserObj.photo || ''
      },
      mutations: {
        // 修改头像
        mUpdateUserPhoto (state, newPhoto) {
          state.photo = newPhoto
          // 持久化
          const { birthday, gender, id, mobile, name, photo } = state
          setUserInfo({ birthday, gender, id, mobile, name, photo })
        },
        // 修改生日
        mUpdateUserBirthday (state, newBirthday) {
          state.birthday = newBirthday
          // 持久化
          const { birthday, gender, id, mobile, name, photo } = state
          setUserInfo({ birthday, gender, id, mobile, name, photo })
        },
        // 修改性别
        mUpdateGender (state, newGender) {
          state.gender = newGender
          // 持久化
          const { birthday, gender, id, mobile, name, photo } = state
          setUserInfo({ birthday, gender, id, mobile, name, photo })
        },
        // 修改姓名
        mUpdateUserName (state, newName) {
          state.name = newName
          // 持久化
          const { birthday, gender, id, mobile, name, photo } = state
          setUserInfo({ birthday, gender, id, mobile, name, photo })
        },
        // 设置用户信息
        mSetUserInfo (state, newUserInfo) {
          state.birthday = newUserInfo.birthday
          state.gender = newUserInfo.gender
          state.id = newUserInfo.id
          state.mobile = newUserInfo.mobile
          state.name = newUserInfo.name
          state.photo = newUserInfo.photo
          // 持久化
          setUserInfo(newUserInfo)
        }
      }
    }
  }
})
